package com.hunttown.mes.common.utils;

/**
 * @title: GPS工具类
 * @author: wangjunfu
 * @date: 2021年10月07日 16:03
 * @description:
 */
public class GPSUtils {

    private static double EARTH_RADIUS = 6371.0; //km 地球半径 平均值，千米

    /**
     * 获取两个坐标之间的距离
     *
     * @return 返回距离（米）
     */
    public static int getDistance(String lat1, String lon1, String lat2, String lon2) {
        if (StringUtils.isBlank(lat1) || StringUtils.isBlank(lon1) || StringUtils.isBlank(lat2) || StringUtils.isBlank(lon2)) {
            return 0;
        }

        double distance = Distance(Double.parseDouble(lat1), Double.parseDouble(lon1), Double.parseDouble(lat2), Double.parseDouble(lon2));
        distance = distance * 1000;
        return new Double(distance).intValue();
    }

    /// <summary>
    /// 给定的经度1，纬度1；经度2，纬度2. 计算2个经纬度之间的距离。
    /// </summary>
    /// <param name="lat1">经度1</param>
    /// <param name="lon1">纬度1</param>
    /// <param name="lat2">经度2</param>
    /// <param name="lon2">纬度2</param>
    /// <returns>距离（公里、千米）</returns>
    public static double Distance(double lat1, double lon1, double lat2, double lon2) {
        //用haversine公式计算球面两点间的距离。
        //经纬度转换成弧度
        lat1 = ConvertDegreesToRadians(lat1);
        lon1 = ConvertDegreesToRadians(lon1);
        lat2 = ConvertDegreesToRadians(lat2);
        lon2 = ConvertDegreesToRadians(lon2);

        //差值
        double vLon = Math.abs(lon1 - lon2);
        double vLat = Math.abs(lat1 - lat2);

        //就是一个球体上的切面，它的圆心即是球心的一个周长最大的圆。
        double h = HaverSin(vLat) + Math.cos(lat1) * Math.cos(lat2) * HaverSin(vLon);

        double distance = 2 * EARTH_RADIUS * Math.asin(Math.sqrt(h));
        return distance;
    }

    private static double HaverSin(double theta) {
        double v = Math.sin(theta / 2);
        return v * v;
    }

    /// <summary>
    /// 将角度换算为弧度。
    /// </summary>
    /// <param name="degrees">角度</param>
    /// <returns>弧度</returns>
    private static double ConvertDegreesToRadians(double degrees) {
        return degrees * Math.PI / 180;
    }

    /// <summary>
    /// 将弧度换算为角度。
    /// </summary>
    /// <param name="degrees">弧度</param>
    /// <returns>角度</returns>
    private static double ConvertRadiansToDegrees(double radian) {
        return radian * 180.0 / Math.PI;
    }

    /// <summary>
    /// 根据经纬度，计算2个点之间的距离。
    /// </summary>
    /// <param name="args"></param>
    public static void main(String[] args) {
        System.out.println("距离为：" + Distance(37.42120849609375, 122.13372368706597, 37.42120849609375, 122.13372368706597));
        System.out.println("距离为：" + getDistance("37.42120849609375", "122.13372368706597", "37.42120849609375", "122.13372368706597"));
    }
}
